package com.github.shiqiyue.xm.util;

import org.springframework.http.ResponseEntity;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/***
 * HttpServeltResponse 工具类
 * @author wenyao.wu
 * @date 2019/7/11
 */
public class ResponseUtils {

    /***
     * 将ResponseEntity 输出到  servletResponse
     * @param responseEntity
     * @param servletResponse
     * @throws IOException
     */
    public static void populateResponse(ResponseEntity responseEntity, HttpServletResponse servletResponse)
            throws IOException {
        for (Map.Entry<String, List<String>> header : responseEntity.getHeaders().entrySet()) {
            String key = header.getKey();
            for (String value : header.getValue()) {
                servletResponse.addHeader(key, value);
            }
        }

        servletResponse.setStatus(responseEntity.getStatusCodeValue());
        Object body = responseEntity.getBody();
        if (body instanceof String) {
            servletResponse.getWriter().write((String) body);
        } else {
            servletResponse.getWriter().write(JsonUtils.beanToString(body));
        }

    }
}
